from flask import Blueprint, render_template, request, redirect, url_for, flash, make_response, session, current_app
from function.sqlite_function import *
from time import localtime

_login = Blueprint('login', __name__, url_prefix='/')


# 显示登录主界面
@_login.route('/login')
def login():
    # 当输入网址时，如果发现session中有授权信息就直接导航到零件管理页面，否则导航至登录页面
    if [session.get('username'), session.get('password'), session.get('identity')] in current_app.member:
        return redirect(url_for('make.make_index'))
    else:
        if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
            # 对应这种场景：一个人登录后清除了cookie并使用ajax发送请求
            return '您的登录权限已失效，请重新登录并询问管理员'
        else:
            return render_template('login/login.html')


# 验证登录信息，如果正确就给出授权
@_login.route('/login1', methods=['POST'])
def login1():
    username = request.form.get('username').strip()
    password = request.form.get('password').strip()
    identity = request.form.get('identity')
    type1 = request.form.get('type1')
    print(username, password, identity, current_app.member)

    if [username, password, identity] in current_app.member:
        session['identity'] = identity
        session['username'] = username
        session['password'] = password
        if type1 == 'month':
            session.permanent = True
        return 'true'
    else:
        return 'false'


# 验证管理员界面登录信息
@_login.route('/master', methods=['POST'])
def login_master():
    username = request.form.get('username_master').strip()
    password = request.form.get('password_master').strip()
    identity = request.form.get('identity_master')
    print(username, password, identity)
    if [username, password, identity] in current_app.member:
        session['username'] = username
        session['password'] = password
        session['identity'] = '管理员'
        return 'true'
    else:
        return 'false'


# 管理员界面
@_login.route('/master1')
def login2():
    con, cur = db_open()
    temp = sqliteObject_to_list_h(cur, f'''
        select * from master ORDER BY identity desc
    ''')
    return render_template('login/master.html', data=temp)


# 添加新账户
@_login.route('/master3', methods=['POST'])
def login3():
    a = request.form.get('user_type')
    b = request.form.get('username1').strip()
    c = request.form.get('password1').strip()
    time = localtime()
    d = f'{time[0]}-{time[1]}-{time[2]}'
    con, cur = db_open()
    sql = '''
        insert into master(
                identity,
                username,
                password,
                creationtime
                )
            values(
                ?,
                ?,
                ?,
                ?
            )
            '''
    cur.execute(sql, (a, b, c, d))
    con.commit()
    # 更新current_app.member列表，将新账户放上去
    update_member()
    return redirect(url_for('login.login2'))


# 删除现有账户
@_login.route('/master4', methods=['POST'])
def login4():
    a = request.form.get('username2').strip()
    if a == current_app.member[0][1] and current_app.member[0][0] == '管理员':
        return redirect(url_for('login.login2'))
    con, cur = db_open()
    sql = f'delete from master where username = "{a}" and identity != "管理员"'
    cur.execute(sql)
    con.commit()
    update_member()
    return redirect(url_for('login.login2'))


# 重置管理员账户的账号和密码
@_login.route('/master5', methods=['POST'])
def login5():
    a = request.form.get('username3').strip()
    b = request.form.get('password3').strip()
    con, cur = db_open()
    sql = f'UPDATE master SET username = "{a}", password = "{b}" WHERE identity = "管理员"'
    cur.execute(sql)
    con.commit()
    update_member()
    session['username'] = a
    session['password'] = b
    update_member()
    return redirect(url_for('login.login2'))


# 从任何页面中点击了退出登录选项
@_login.route('/quit', methods=['POST'])
def login_quit():
    session.clear()
    return '注销成功'


# 更新全局变量中的用户名单
def update_member():
    con, cur = db_open()
    current_app.member = sqliteObject_to_list_h(cur, f'''
        select username, password, identity from master
    ''')
